package ru.smc.hogwarts.servlets.choice;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.model.Student;
import ru.smc.hogwarts.model.StudentSubject;
import ru.smc.hogwarts.model.Subject;

public class ChoiceSubjects extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private HttpSession session;
	private String error = "";
	private int id;
    private List <Subject> subjects;
	
    
	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		error = "";
		EntityManagerFactory emf = EMF.getInstance().getEMF();
   	    EntityManager em = emf.createEntityManager();
   	    session = request.getSession(true);
		id=(Integer)session.getAttribute("userID");
		request.setAttribute("error", error);
		long dupl = 0;
		Date date = new Date(); 
		Calendar currentCal = Calendar.getInstance();
		currentCal.setTime(date); 
		Calendar cal = Calendar.getInstance(); 
		cal.setTime(date);
		cal.set(Calendar.DAY_OF_MONTH,1);
		cal.set(Calendar.MONTH,Calendar.JUNE);
		cal.set(Calendar.HOUR, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0); 
		Calendar cal2 = Calendar.getInstance(); 
		cal2.setTime(date);
		cal2.set(Calendar.DAY_OF_MONTH,31);
		cal2.set(Calendar.MONTH,Calendar.JULY);
		cal2.set(Calendar.HOUR, 0);
		cal2.set(Calendar.MINUTE, 0);
		cal2.set(Calendar.SECOND, 0);
		cal2.set(Calendar.MILLISECOND, 0);
		
		Query query = em.createQuery("select s.year from Student s where s.person.id=?1");
		query.setParameter(1, id);
		int year = (Integer) query.getSingleResult();
		
		query = em.createQuery("select COUNT(a.id) from Assessment a where a.student.person.id=?1 and a.grade='У' and a.subject.year=?2");
		query.setParameter(1, id);
		query.setParameter(2, year);
		long grades = (Long) query.getSingleResult();
		
		query = em.createQuery("select COUNT(s.id) from StudentSubject s where s.student.person.id=?1 and s.subject.year=?2");
		query.setParameter(1, id);
		query.setParameter(2, year);
		
		try {
			dupl = (Long) query.getSingleResult();
		}
		catch (NoResultException e){}
		
		if (dupl > 0){
			error="<span>В</span>ы уже выбрали дополнительные дисциплины в этом году.";
			request.setAttribute("error", error);
			request.getRequestDispatcher("/pages/choice_subjects/error.jsp").forward(request, response);
		} 
		else {
			if ((currentCal.before(cal) || currentCal.after(cal2)) && (dupl < 1)){
				error="<span>В</span>ыбирать можно только между 1 июня и 31 июля.";
				request.setAttribute("error", error);
				request.getRequestDispatcher("/pages/choice_subjects/error.jsp").forward(request, response);
			}
			else {
				if (grades>2){
					error="<span>У</span> Вас слишком плохая успеваемость. Вы не можете выбирать предметы.";
					request.setAttribute("error", error);
					request.getRequestDispatcher("/pages/choice_subjects/error.jsp").forward(request, response);
				}
				else {
					Query query2 = em.createQuery("select s from Subject s where s.year=?1 and s.type='по выбору'");
					query2.setParameter(1,year);
					subjects = query2.getResultList();
					request.setAttribute("subjects", subjects);
					request.getRequestDispatcher("/pages/choice_subjects/choice.jsp").forward(request, response);
				}
			}
		}
		
		em.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		EntityManagerFactory emf = EMF.getInstance().getEMF();
   	    EntityManager em = emf.createEntityManager();
		String[] arsid = request.getParameterValues("subject_id");
		id=(Integer)session.getAttribute("userID");
		
		Query query = em.createQuery("select s from Student s where s.person.id=?1");
		query.setParameter(1, id);
		Student student = (Student) query.getSingleResult();
		try {
			for (String sid : arsid) {
				em.getTransaction().begin();
				Subject subject = em.find(Subject.class, sid);
				StudentSubject ss = new StudentSubject();
				ss.setStudent(student);
				ss.setSubject(subject);
				em.persist(ss);
				em.getTransaction().commit();
			}
			request.getRequestDispatcher("/pages/choice_subjects/ok.jsp").forward(request, response);
		}	
		catch (NullPointerException e) {
			error = "<span>В</span>ыберите одну или несколько дисциплин из списка.";
			request.setAttribute("error", error);
			request.setAttribute("subjects", subjects);
			request.getRequestDispatcher("/pages/choice_subjects/choice.jsp").forward(request, response);
		}

		em.close();
	}

}
